package com.toman.ui.work.workshop;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.toman.Adpter.ItemListAdapter;
import com.toman.Enum.BaseEnum;
import com.toman.Enum.PermEnum;
import com.toman.Interfaces.NewBaseUrl;
import com.toman.JavaBean.PlanEntity;
import com.toman.JavaBean.ProductEntity;
import com.toman.R;
import com.toman.Util.BaseNetUtil;
import com.toman.Util.JsonUtils;
import com.toman.Util.PermissonUtils;
import com.toman.Util.ToastUtil;
import com.toman.Util.ViewUtil;
import com.toman.bean.ItemListBean;
import com.toman.toolbar.ToolBarActivity;
import com.toman.widget.CustomProgressBar;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Request;
import okhttp3.Response;

public class PlanInfActivity extends ToolBarActivity {
    boolean expand_product = true;
    boolean expand_order = true;
    String status;
    PlanEntity bean;
    @BindView(R.id.tv_progress)
    TextView tvProgress;
    @BindView(R.id.pb_base)
    CustomProgressBar pbBase;

    @BindView(R.id.iv_product)
    ImageView ivProduct;
    @BindView(R.id.rl_product)
    RelativeLayout rlProduct;
    @BindView(R.id.tv_dep)
    TextView tvDep;
    @BindView(R.id.rl_product_dep)
    RelativeLayout rlProductDep;
    @BindView(R.id.tv_beltline)
    TextView tvBeltline;
    @BindView(R.id.rl_product_beltline)
    RelativeLayout rlProductBeltline;

    @BindView(R.id.tv_product_name)
    TextView tvProductName;
    @BindView(R.id.tv_product_size)
    TextView tvProductSize;
    @BindView(R.id.tv_product_mode)
    TextView tvProductMode;
    @BindView(R.id.tv_product_unit)
    TextView tvProductUnit;
    @BindView(R.id.ll_device_more)
    LinearLayout llDeviceMore;
    @BindView(R.id.ll_device)
    LinearLayout llDevice;
    @BindView(R.id.iv_order)
    ImageView ivOrder;
    @BindView(R.id.rl_order)
    RelativeLayout rlOrder;
    @BindView(R.id.et_order_plan_code)
    EditText etOrderPlanCode;
    @BindView(R.id.rl_order_code)
    RelativeLayout rlOrderCode;
    @BindView(R.id.et_order_num)
    EditText etOrderNum;
    @BindView(R.id.rl_order_num)
    RelativeLayout rlOrderNum;
    @BindView(R.id.et_order_code)
    EditText etOrderCode;

    @BindView(R.id.et_order_need)
    EditText etOrderNeed;
    @BindView(R.id.tv_order_lastday)
    TextView tvOrderLastday;
    @BindView(R.id.tv_order_remark_name)
    TextView tvOrderRemarkName;
    @BindView(R.id.et_order_remark)
    EditText etOrderRemark;
    @BindView(R.id.ll_order_more)
    LinearLayout llOrderMore;
    @BindView(R.id.tv_check_man)
    TextView tvCheckMan;
    @BindView(R.id.tv_check_time)
    TextView tvCheckTime;
    @BindView(R.id.tv_edit_man)
    TextView tvEditMan;
    @BindView(R.id.tv_edit_time)
    TextView tvEditTime;
    @BindView(R.id.ll_check)
    LinearLayout llCheck;
    @BindView(R.id.ll_order)
    LinearLayout llOrder;
    @BindView(R.id.rl_check)
    RelativeLayout rlCheck;
    @BindView(R.id.rl_check_time)
    RelativeLayout rlCheckTime;
    @BindView(R.id.rl_progress)
    RelativeLayout rlProgress;
    @BindView(R.id.tv_qualified_count)
    TextView tvQualifiedCount;
    @BindView(R.id.tv_waste_count)
    TextView tvWasteCount;
    @BindView(R.id.tv_scrapped_count)
    TextView tvScrappedCount;
    @BindView(R.id.tv_remake_count)
    TextView tvRemakeCount;
    @BindView(R.id.tv_reuse_count)
    TextView tvReuseCount;
    @BindView(R.id.tv_completed_count)
    TextView tvCompletedCount;
    @BindView(R.id.tv_demand_count)
    TextView tvDemandCount;
    @BindView(R.id.tv_product_code)
    TextView tvProductCode;
    @BindView(R.id.et_customer)
    EditText etCustomer;
    ItemListAdapter adapter;
    List<ItemListBean> list = new ArrayList<>();
    List<ProductEntity> list_product = new ArrayList<>();
    @BindView(R.id.tv_dep_title)
    TextView tvDepTitle;
    @BindView(R.id.tv_product_name_title)
    TextView tvProductNameTitle;
    @BindView(R.id.tv_beltline_title)
    TextView tvBeltlineTitle;
    @BindView(R.id.et_order_need_titile)
    TextView etOrderNeedTitile;
    @BindView(R.id.tv_order_lastday_title)
    TextView tvOrderLastdayTitle;
    @BindView(R.id.rl_editman)
    RelativeLayout rlEditman;
    @BindView(R.id.rl_edittime)
    RelativeLayout rlEdittime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_plan_inf);
        ButterKnife.bind(this);
        initToolBar("车间计划详情");
        initIntent();
        initView();
    }

    private void initView() {
        tvDep.setText(bean.getDepartmentEntity().getDepartmentName());
        tvBeltline.setText(bean.getOperationArtlineEntity().getArtlineName());
        tvProductCode.setText(bean.getProductEntity().getProductCode());
        tvProductName.setText(bean.getProductEntity().getProductName());
        tvProductSize.setText(bean.getProductEntity().getProductSize());
        tvProductMode.setText(bean.getProductEntity().getProductMode());
        tvProductUnit.setText(bean.getProductEntity().getProductUnit());
        etOrderPlanCode.setText(bean.getPlanNum());
        etOrderNum.setText(bean.getPlanOrderNum());
        etOrderCode.setText(bean.getOrderNum());
        etCustomer.setText(bean.getCustomer());
        etOrderNeed.setText(bean.getDemandCount() + "");
        tvOrderLastday.setText(bean.getProvideDate());
        etOrderRemark.setText(bean.getRemark());

        ViewUtil.unedit(etCustomer, etOrderRemark, etOrderNeed, etOrderNum, etOrderPlanCode, etOrderCode);
        ViewUtil.unclick(tvDep, tvProductName, tvBeltline, tvOrderLastday);
        if (status.equals("0")) {
            ViewUtil.gone(rlCheck, rlCheckTime, rlProgress);
        } else {
//            bean.getPlanCompleteCount().setCompletedCount(500L);

            tvCheckMan.setText(bean.getAuditUser().getRealName());
            tvCheckTime.setText(bean.getAuditTime());
            tvQualifiedCount.setText("合格数量:" + bean.getPlanCompleteCount().getQualifiedCount() + "");
            tvScrappedCount.setText("报废数量:" + bean.getPlanCompleteCount().getScrappedCount() + "");
            tvCompletedCount.setText(bean.getPlanCompleteCount().getCompletedCount() + "");
            tvWasteCount.setText("料废数量:" + bean.getPlanCompleteCount().getWasteCount() + "");
            tvRemakeCount.setText("返工数量:" + bean.getPlanCompleteCount().getRemakeCount() + "");
            tvReuseCount.setText("回用数量:" + bean.getPlanCompleteCount().getReuseCount() + "");
            tvDemandCount.setText(bean.getDemandCount() + "");
            pbBase.setMaxProgress((Integer.parseInt(bean.getDemandCount() + "")));
            if (bean.getDemandCount() >= bean.getPlanCompleteCount().getCompletedCount()) {
                pbBase.setCurProgress(Integer.parseInt(bean.getPlanCompleteCount().getCompletedCount() + ""), 2000);
            } else {
                pbBase.setCurProgress(Integer.parseInt(bean.getDemandCount() + ""), 2000);
            }
            if (status.equals("1")) {
                ViewUtil.done(tvProductName, tvBeltline);

            }
            if (status.equals("2")) {
ViewUtil.visible(rlEditman,rlEdittime);
                tvEditMan.setText(bean.getCompleteUser().getRealName());
                tvEditTime.setText(bean.getCompleteTime());
                ViewUtil.done(tvDep, tvProductName, tvBeltline, tvOrderLastday);

            }
        }

    }

    private void initIntent() {
        adapter = new ItemListAdapter(this);
        status = getIntent().getStringExtra("status");
        bean = (PlanEntity) getIntent().getSerializableExtra("bean");
    }

    public void dilogDep() {
        final AlertDialog dialog;
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LayoutInflater factory = LayoutInflater.from(this);
        final View textEntryView = factory.inflate(R.layout.dialog_list, null);
        ListView lv = (ListView) textEntryView.findViewById(R.id.lv);
        lv.setAdapter(adapter);
        builder                //对话框的标题
                .setTitle("选择部门")
                //设定显示的View
                .setView(textEntryView)
                //对话框中的“登陆”按钮的点击事件
                .setPositiveButton("取消", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                        //获取用户输入的“用户名”，“密码”
                    }
                })
                //对话框的“退出”单击事件
//                .setNegativeButton("退出", new DialogInterface.OnClickListener() {
//                    public void onClick(DialogInterface dialog, int whichButton) {
//                    }
//                })
                // 设置dialog是否为模态，false表示模态，true表示非模态
                .setCancelable(true)
                .create();
        dialog = builder.show();
        BaseNetUtil.dep(this, list, token, mCompanyId, adapter);
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                ItemListBean bean1 = adapter.getItem(i);
                bean.getDepartmentEntity().setDepartmentName(bean1.getName());
                bean.getDepartmentEntity().setId(Long.valueOf(bean1.getID()));
                tvDep.setText(bean.getDepartmentEntity().getDepartmentName());
                dialog.dismiss();
            }
        });
    }

    public void dilogProduct() {
        final AlertDialog dialog;
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LayoutInflater factory = LayoutInflater.from(this);
        final View textEntryView = factory.inflate(R.layout.dialog_list, null);
        ListView lv = (ListView) textEntryView.findViewById(R.id.lv);
        lv.setAdapter(adapter);
        builder                //对话框的标题
                .setTitle("选择品名")
                //设定显示的View
                .setView(textEntryView)
                //对话框中的“登陆”按钮的点击事件
                .setPositiveButton("取消", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                        //获取用户输入的“用户名”，“密码”
                    }
                })
                //对话框的“退出”单击事件
//                .setNegativeButton("退出", new DialogInterface.OnClickListener() {
//                    public void onClick(DialogInterface dialog, int whichButton) {
//                    }
//                })
                // 设置dialog是否为模态，false表示模态，true表示非模态
                .setCancelable(true)
                .create();
        dialog = builder.show();
        list_product = BaseNetUtil.product(this, list, token, mCompanyId, adapter);

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                ItemListBean bean1 = adapter.getItem(i);
                bean.setProductEntity(list_product.get(i));
                tvProductName.setText(bean.getProductEntity().getProductName());
                tvProductMode.setText(bean.getProductEntity().getProductMode());
                tvProductUnit.setText(bean.getProductEntity().getProductUnit());
                tvProductSize.setText(bean.getProductEntity().getProductSize());
                tvProductCode.setText(bean.getProductEntity().getProductCode());
                tvBeltline.setText(bean.getProductEntity().getArtlineEntity().getArtlineName());

                dialog.dismiss();
            }
        });
    }

    public void dilogArtLine() {
        final AlertDialog dialog;
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LayoutInflater factory = LayoutInflater.from(this);
        final View textEntryView = factory.inflate(R.layout.dialog_list, null);
        ListView lv = (ListView) textEntryView.findViewById(R.id.lv);
        lv.setAdapter(adapter);
        builder                //对话框的标题
                .setTitle("选择工艺线路")
                //设定显示的View
                .setView(textEntryView)
                //对话框中的“登陆”按钮的点击事件
                .setPositiveButton("取消", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                        //获取用户输入的“用户名”，“密码”
                    }
                })
                //对话框的“退出”单击事件
//                .setNegativeButton("退出", new DialogInterface.OnClickListener() {
//                    public void onClick(DialogInterface dialog, int whichButton) {
//                    }
//                })
                // 设置dialog是否为模态，false表示模态，true表示非模态
                .setCancelable(true)
                .create();
        dialog = builder.show();
        BaseNetUtil.artline(this, list, token, mCompanyId, adapter, bean.getProductEntity().getProductName());

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                ItemListBean bean1 = adapter.getItem(i);
                bean.getOperationArtlineEntity().setArtlineName(bean1.getName());
                bean.getOperationArtlineEntity().setId(Long.valueOf(bean1.getID()));
                tvBeltline.setText(bean.getOperationArtlineEntity().getArtlineName());

                dialog.dismiss();
            }
        });
    }

    public void add() {
        String[] item = new String[]{"部门", "最后交付日", "净需求数", "品名", "工艺路线名称"};//直接初始化
        if (ViewUtil.isNull(getApplicationContext(), item, tvDep, tvOrderLastday, etOrderNeed, tvProductName, tvBeltline)) {
            return;
        }
        Map<String, String> map = new HashMap<String, String>();
        map.put("departmentId", bean.getDepartmentEntity().getId() + "");
        map.put("id", bean.getId() + "");
        map.put("planNum", etOrderPlanCode.getText().toString());
        map.put("planOrderNum", etOrderNum.getText().toString());
        map.put("customer", etCustomer.getText().toString());
        map.put("orderNum", etOrderCode.getText().toString());
        map.put("provideDate", tvOrderLastday.getText().toString());
        map.put("demandCount", etOrderNeed.getText().toString());
        map.put("productId", bean.getProductEntity().getId() + "");
        map.put("artlineId", bean.getOperationArtlineEntity().getId() + "");
        map.put("remark", etOrderRemark.getText().toString());

        String str = JsonUtils.obj2JsonString(map);
        OkHttpUtils
                .post(NewBaseUrl.workshop_plan_update)
                .headers("token", token)
                .headers("Content-Type", "application/json")
                .postJson(str)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "新增班次: " + result);
                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");
                        ViewUtil.lagout(code, getApplicationContext());

                        if (code == 0) {
                            ToastUtil.makeText(getApplicationContext(), jsonObj.getString("msg"));
                            finish();

                        } else {
                            ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                        }

                    }
                });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.toolbar_edit, menu);


        MenuItem menuItem = menu.findItem(R.id.menu_edit);
        if (status.equals("2") || status.equals("3")) {
            menuItem.setVisible(false);
        }
        if (!PermissonUtils.contains(this, BaseEnum.PLAN.has(PermEnum.EDIT))) {
            menuItem.setVisible(false);
        }
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {

            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.menu_edit:
                        if (item.getTitle().equals("编辑")) {
                            item.setTitle("完成");
                            switch (status) {
                                case "0":
                                    ViewUtil.edit(etCustomer, etOrderRemark, etOrderNeed, etOrderCode);
                                    ViewUtil.click(tvDep, tvProductName, tvBeltline, tvOrderLastday);
                                    ViewUtil.necessary(tvProductNameTitle, tvDepTitle, etOrderNeedTitile, tvOrderLastdayTitle, tvBeltlineTitle);
                                    break;

                                case "1":
                                    ViewUtil.edit(etOrderRemark, etOrderNeed);
                                    ViewUtil.click(tvOrderLastday);
                                    ViewUtil.necessary(tvProductNameTitle, tvDepTitle, etOrderNeedTitile, tvOrderLastdayTitle, tvBeltlineTitle);


                                    break;
                            }


                        } else {
                            switch (status) {
                                case "0":
                                    add();
                                    break;

                                case "1":
                                    add();
                                    break;
                            }

                        }
                        break;
                }
                return false;
            }
        });

        return true;
    }

    @OnClick({R.id.rl_product, R.id.rl_order, R.id.tv_dep, R.id.tv_order_lastday, R.id.tv_product_name, R.id.tv_beltline})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_product:
                if (expand_product) {
                    llDeviceMore.setVisibility(View.GONE);
                    ivProduct.setImageResource(R.mipmap.down);
                } else {
                    llDeviceMore.setVisibility(View.VISIBLE);
                    ivProduct.setImageResource(R.mipmap.upward);

                }
                expand_product = !expand_product;
                break;
            case R.id.rl_order:
                if (expand_order) {
                    llOrderMore.setVisibility(View.GONE);
                    ivOrder.setImageResource(R.mipmap.down);
                } else {
                    llOrderMore.setVisibility(View.VISIBLE);
                    ivOrder.setImageResource(R.mipmap.upward);

                }
                expand_order = !expand_order;

                break;
            case R.id.tv_dep:
                dilogDep();
                break;
            case R.id.tv_product_name:
                dilogProduct();
                break;
            case R.id.tv_order_lastday:
                ViewUtil.getDate(this, tvOrderLastday);
                break;
            case R.id.tv_beltline:
                dilogArtLine();
                break;
        }
    }
}
